<template>
  <el-dialog
    v-el-drag-dialog
    title="新增盘点"
    :visible.sync="visible"
    width="1200px"
  >
    <el-form ref="form" :model="form" :inline="true">
      <el-form-item label="仓库名称" prop="storeId">
        <el-select v-model="form.storeId" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.rName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点人员" prop="name">
        <el-input v-model="form.operator" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="盘点日期">
        <el-date-picker v-model="form.date" type="date" disabled />
      </el-form-item>
      <el-form-item label="备注" prop="name">
        <el-input v-model="form.operator" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品类型" prop="csmTypeSource">
        <el-select v-model="form.gtId" placeholder="请选择">
          <el-option
            v-for="item in goodsTypeMap"
            :key="item.gtId"
            :label="item.gtName"
            :value="item.gtId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-select
          v-model="form.goodsId"
          placeholder="请选择"
          @change="goodsIdSelect"
        >
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in goodsMap"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="item.goodsId"
          />
        </el-select>
      </el-form-item>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >添加</el-button>
    </el-form>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      @fetch="fetchData"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    selectOrgSNNoAndReType,
    goodsTypeQueryList,
    floorfeeSelectList,
    querystoreDetailList,
    stockCheck
  } from '@/api'
  import { formatColumnMap } from '@/utils'
  export default {
    name: 'add',
    data() {
      return {
        visible: false,
        form: {
          date: new Date()
        },
        selectedGd: {},
        storeMap: [], // 仓库名称
        goodsTypeMap: [], // 商品类型
        goodsMap: [], // 商品名称
        statusMap: [
          { value: 1, desc: '重', key: 'HEAVY' },
          { value: 2, desc: '轻', key: 'LIGHT' },
          { value: 3, desc: '回收', key: 'RECYCLE' },
          { value: 4, desc: '故障', key: 'BROKEN' },
          { value: 5, desc: '已损坏', key: 'CORRUPT' },
          { value: 6, desc: '正常', key: 'NORMAL' },
          { value: 7, desc: '报废', key: 'SCRAPPED' },
          { value: 8, desc: '过期', key: 'EXPIRED' },
          { value: 9, desc: '问题重瓶', key: 'QUEHEAVY' }
        ],
        tableData: {
          column: [
            {
              prop: 'gtName',
              label: '商品类型'
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              renderHeader: (h, { row }) => {
                return (
                <el-tooltip
                  class='item'
                  effect='dark'
                  content='默认加载仓库中有数据的商品，可在上方选择其他商品点击添加'
                  placement='top-start'
                >
                  <i class='el-icon-question'>
                    <span>商品名称</span>
                  </i>
                </el-tooltip>
                )
              }
            },
            {
              prop: 'specCode',
              label: '规格型号'
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, scope) => (

              <div>
                  {scope.row._edit ? (
                    <el-select value={ scope.row[scope.column.property] }
                          style='width: 80px'
                          onChange={ (val) => { scope.row[scope.column.property] = val } }>
                          {
                            this.statusMap.map(option => {
                              return (
                                <el-option label={ option.desc } value={ option.value }></el-option>
                              )
                            })
                          }
                        </el-select>
                  ) : (
                      <span>
                        {scope.row.gdStatus &&
                          formatColumnMap(
                            this.statusMap,
                            'value',
                            scope.row.gdStatus,
                            'desc'
                          )}
                      </span>
                  )}
                </div>

            )
            },
            {
              prop: 'gdCount',
              label: '账面库存',
              render: (h, { row }) => {
                return <span>{row.gdCount + row.unitName}</span>
              }
            },
            {
              prop: 'realCount',
              label: '实际库存',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '盈/亏数量',
              render: (h, { row, $index }) =>
                row.realCount - row.gdCount === 0 ? (
                <span></span>
                  ) : (
                <span style='color:red'>
                  {row.realCount - row.gdCount > 0
                    ? '+' + (row.realCount - row.gdCount)
                    : row.realCount - row.gdCount}
                </span>
              )
            },
            {
              prop: 'remark',
              label: '备注',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-button
                        type='primary'
                        onClick={() => {
                          this.handleSave(scope)
                        }}
                      >
                        保存
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.handleCancle(scope)
                        }}
                      >
                        取消
                      </el-button>
                    </div>
                  ) : (
                    <el-button
                      type='primary'
                      onClick={() => {
                        this.handleEdit(scope)
                      }}
                    >
                      编辑
                    </el-button>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    watch: {
      'form.gtId': function(val) {
        this.form.goodsId = 0
        this.getgoodsListBygtId()
      },
      'form.storeId': function(val) {
        this.fetchData()
      }
    },
    created() {
      this.initStoreMap()
      this.initStste()
    },
    methods: {
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )

        const json = {
          storeId: this.form.storeId,
          storeName: this.form.storeName,
          remark: this.form.remark,
          detailList: [scope.row]
        }
        stockCheck(json).then(res => {
          if (res.success) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '操作失败！',
              type: 'error'
            })
          }
        })
      },
      handleCancle(scope) {
        this.$set(
          this.tableData.data,
          scope.$index,
          JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
        )
      },
      open(temp) {
        this.visible = true
      },
      goodsIdSelect(val) {
        const goodsMap = this.goodsMap
        goodsMap.forEach((item, index, row) => {
          if (item.goodsId === val) {
            this.selectedGd = item
            console.log(item)
          }
        })
      },
      initStste() {
        goodsTypeQueryList().then(res => {
          this.goodsTypeMap = res.data
        })
      },
      success() {},
      add() {
        if (!this.form.gtId) {
          this.$message({
            message: '请选择商品类型！',
            type: 'error'
          })
          return
        }
        if (!this.form.goodsId) {
          this.$message({
            message: '请选择商品名称！',
            type: 'error'
          })
          return
        }
        const selectedGd = this.selectedGd
        const insertObj = {
          goodsId: selectedGd.goodsId,
          goodsName: selectedGd.goodsName,
          gtId: selectedGd.gTypeId,
          gtName: selectedGd.gtName,
          gtSNNo: selectedGd.gtSNNo,
          pricingMode: selectedGd.pricingMode,
          goodsCode: selectedGd.goodsCode,
          specCode: selectedGd.specCode,
          goodsSpec: selectedGd.specName,
          unitId: selectedGd.unitId,
          unitName: selectedGd.unitName,
          goodStatus: selectedGd.gdStatus,
          gdCount: 0,
          realCount: 0,
          lessCount: 0,
          netWeight: 0,
          realNetWeight: 0
        }

        this.tableData.data.unshift(insertObj)
        this.tableData.defaultData.unshift(JSON.parse(JSON.stringify(insertObj)))
      },
      fetchData() {
        const storeId = this.form.storeId
        querystoreDetailList({
          storeId: storeId,
          pageIndex: 1,
          pageSize: 999,
          sortBy: -1
        }).then(res => {
          const rows = this.rowsFormater(res.data.rows)
          this.tableData.data = rows
          this.tableData.defaultData = JSON.parse(JSON.stringify(rows))
        })
      },
      initStoreMap() {
        selectOrgSNNoAndReType({
          reType: 4
        }).then(res => {
          this.storeMap = res.data
        })
      },
      rowsFormater(rows) {
        rows.forEach((item, index, rows) => {
          item.remark = ''
          item.realCount = item.gdCount
        })
        return rows
      },
      getgoodsListBygtId() {
        const gtId = this.form.gtId
        floorfeeSelectList({
          gtId: gtId,
          pageIndex: 1,
          pageSize: 999
        }).then(res => {
          this.goodsMap = res.data.rows
        })
      }
    }
  }
</script>

<style lang="scss" scoped></style>
